#include<iostream>
#include<string>
#include<sstream>
#include<memory>
#include<jsoncpp/json/json.h>
    static Json::Value def = []()
    {
        Json::Value def;
        Json::StreamWriterBuilder::setDefaults(&def);
        def["emitUTF8"] = true;
        return def;
    }();

bool Serialization(Json::Value val,std::string&body)
{

    
    Json::StreamWriterBuilder swb;
    swb.settings_ = def;
    std::unique_ptr<Json::StreamWriter>sw (swb.newStreamWriter());
    std::stringstream ss;
    int ret = sw->write(val, &ss);
    if(ret!=0)
    {
        std::cout << "Serialization failed!";
        return false;
    }
    body = ss.str();
    return true;
}

bool UnSerialization(const std::string &body,Json::Value &val)
{
    //先实例化一个工厂类
    Json::CharReaderBuilder crb;
    //生产CharReader对象
    std::unique_ptr<Json::CharReader>cr(crb.newCharReader());
    //调用CharReader的parse函数分解String对象为Json对象
    Json::String errs;
   bool success = cr->parse(body.c_str(), body.c_str() + body.size(), &val, &errs);
    if(!success)
    {
        std::cout << " UnSerialization failed:"<<errs<<std::endl;
        return false;
    }

    return true;
}

int  main()
{
    const char *name = "张三";
    const char *sex = "男";
    int age = 17;
    int scroe[4] = {80, 90, 99, 100};
    Json::Value stu;

    stu["姓名"] = name;
    stu["性别"] = sex;
    stu["年龄"] = age;
    stu["成绩"].append(scroe[0]);
    stu["成绩"].append(scroe[1]);
    stu["成绩"].append(scroe[2]);
    stu["成绩"].append(scroe[3]);

    Json::Value fav;
    fav["书籍"] = "西游记";
    fav["运动"] = "打篮球";
    fav["休闲"] = "喝茶";

    stu["爱好"] = fav;
   std:: string body;
    Serialization(stu, body);
   // std::cout << body << std::endl;

    Json::Value student;
    std::string str = R"({"姓名":"小黑","年龄":18, "性别":"男", "成绩":[100 ,99, 98]})";
    int ret = UnSerialization(str, student);
    if(!ret)
    {
        return -1;
    }

    std::cout << "姓名：" << student["姓名"].asString() << std::endl;
    std::cout << "年龄：" << student["年龄"].asInt() << std::endl;
    std::cout << "性别：" << student["性别"].asString() << std::endl;
    for (int i = 0; i < student["成绩"].size();i++)
    {
        std::cout << "成绩：" << student["成绩"][i].asString() << std::endl;
    }
        return 0;
}
